package com.hoo.common.mock;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.io.FileUtil;
import cn.hutool.script.JavaScriptEngine;
import cn.hutool.script.ScriptUtil;

import java.io.File;

/**
 * 基于mock的数据库标准函数实现
 *
 * @author hank
 * @create 2020-07-25 下午1:02
 **/

public class MockDbUtil {

    private static Cache<String,String> lfuCache = CacheUtil.newLFUCache(1);
    private static JavaScriptEngine scriptEngine = ScriptUtil.getJavaScriptEngine();

    private static Object buildMock(String script) throws Exception {
        if(lfuCache.isEmpty()) {
            String mock = FileUtil.readUtf8String(new File("/Users/hank/WORK/hoo-platform-parent/hoo-base-parent/hoo-security-mock/src/main/resources/mock/mock-min.js"));
            lfuCache.put("scriptString", mock, DateUnit.SECOND.getMillis() * 30);
            scriptEngine.eval(mock);
        }
        String db = FileUtil.readUtf8String(new File("/Users/hank/WORK/hoo-platform-parent/hoo-base-parent/hoo-security-mock/src/main/resources/mock/mock.db.js"));
        StringBuilder exe = new StringBuilder(db);
        return scriptEngine.eval(exe.append(script.contains("Mock.mock") ? script : String.format("Mock.mock('%s')", script)).toString());
    }

    public static Object parse(String script) {
        try {
            return buildMock(script);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
